import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user/index";
import {
  loginParamData,
  loginResponseData,
  responseUserInfoData,
  logoutResponseData,
} from "@/api/user/type";
import { userState } from "./types/type";
import { constRoutes, asyncRoutes, anyRoute } from "../../router/routes";
import router from "../../router";
// @ts-ignore
import cloneDeep from "lodash/cloneDeep";
// 定义过滤异步路由的函数
const filterAsyncRoute = (asyncRoutes: any, routes: any) => {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length >= 1) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
};
const useUserStore = defineStore("user", {
  state: (): userState => {
    return {
      token: localStorage.getItem("TOKEN"),
      routes: constRoutes,
      username: "",
      avatar: "",
      buttons: [],
    };
  },
  actions: {
    // 用户登录的action
    async userLogin(data: loginParamData) {
      let res: loginResponseData = await reqLogin(data);
      if (res.code === 200) {
        this.token = res.data as string;
        localStorage.setItem("TOKEN", res.data as string);
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    // 获取用户信息的action
    async getUserInfo() {
      let res: responseUserInfoData = await reqUserInfo();
      if (res.code == 200) {
        // 调用函数过滤出是展示的异步路由
        let userAsyncRoutes: any = filterAsyncRoute(
          cloneDeep(asyncRoutes),
          res.data.routes
        );
        this.username = res.data.name;
        this.avatar = res.data.avatar;
        this.buttons = res.data.buttons;
        (this.routes as any) = [...constRoutes, ...userAsyncRoutes, anyRoute];
        [...userAsyncRoutes, anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return "ok";
      } else {
        return Promise.reject(res.message);
      }
    },
    // 用户退出的action
    async userLogout() {
      let res: logoutResponseData = await reqLogout();
      if (res.code == 200) {
        this.username = "";
        this.avatar = "";
        this.token = "";
        localStorage.removeItem("TOKEN");
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
  },
  getters: {},
});
export default useUserStore;
